import net from "node:net";
import nodemailer from "nodemailer";

export function isPortOccupied(port, callback) {
  const server = net.createServer();
  server.listen(port);

  server.on("listening", () => {
    server.close();
    callback(false);
  });

  server.on("error", (err: any) => {
    if (err.code === "EADDRINUSE") {
      console.log(`port ${port} is occupied`);
      callback(true);
    } else {
      console.log(err);
    }
  });
}

// 在有html，并且支持html时，text无效
interface Mail {
  from: string;
  to: string;
  subject: string;
  text: string;
  html: string;
}

export function sendMail(main: Mail): Promise<unknown> {
  const user = "3193299580@qq.com";
  const pass = "wjjuteytnrhidfjd";

  const transporter = nodemailer.createTransport({
    host: "smtp.qq.com",
    port: 587,
    secure: false, // Use `true` for port 465, `false` for all other ports
    auth: { user, pass },
  });

  main.from = user;

  return transporter.sendMail(main);
}
